package org.smth.search.parser.impl;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.smth.search.parser.ContentParser;
import org.smth.search.parser.PostItemParser;
import org.smth.search.types.BoardInfo;
import org.smth.search.types.PostItem;
import org.smth.search.types.impl.BoardInfoImpl;
import org.smth.search.types.impl.PostItemImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Singleton
public class PostItemParserImpl implements PostItemParser {

	@Inject
	private ContentParser contentParser;

	private Log log = LogFactory.getLog(this.getClass());

	private String reg1 = "^.*new.*docWriter\\('\\w+',(\\w+),(\\d+),\\d+,\\d+,(\\d+),(\\d+),'.+',\\d+,\\d+\\);$";

	//   1   版面id     2   开始文章序号    3    总页面数         4   结束文章序号
	private Pattern pattern1 = Pattern.compile(reg1, Pattern.MULTILINE);

	private String reg2 = "^c\\.o\\((\\d+),(\\d+),'(\\w+)','(.+)',(\\d+),'(.+)',(\\d+),\\w+\\);$";

	//       id   firstId  author   flag   time   title   size
	private Pattern pattern2 = Pattern.compile(reg2, Pattern.MULTILINE);

	public BoardInfo getPageCount(String content) {
		Matcher matcher = pattern1.matcher(content);
		BoardInfoImpl info = new BoardInfoImpl();
		if (matcher.find()) {
			info.setPageCount(Integer.parseInt(matcher.group(3)));
			info.setBoardId(matcher.group(1));
		} else {
			log.warn("找总页数失败");
			info.setPageCount(0);
		}
		return info;
	}

	public PostItem[] parsePostItems(String content, boolean withTop) {
		Matcher matcher = pattern2.matcher(content);
		List<PostItem> list = null;
		while (matcher.find()) {
			if (list == null) {
				list = new ArrayList<PostItem>();
			}
			PostItemImpl item = new PostItemImpl();
			item.setId(Integer.parseInt(matcher.group(1)));
			item.setFirstId(Integer.parseInt(matcher.group(2)));
			item.setAuthor(matcher.group(3));
			item.setFlag(matcher.group(4));
			item.setTime(Long.parseLong(matcher.group(5)));
			item.setTitle(contentParser.decodeString(matcher.group(6)));
			item.setSize(Long.parseLong(matcher.group(7)));
			if (withTop || item.getFlag().indexOf('d') < 0) {
				list.add(item);
			}
		}
		if (list == null) {
			log.warn("找条目失败");
			return null;
		} else {
			PostItem[] items = new PostItem[list.size()];
			items = list.toArray(items);
			return items;
		}
	}
}
